Page({
  data: {
    rules: [
      {
        name: 'name',
        rule: ['required'],
        msg: ['请输入收货人姓名']
      },
      {
        name: 'mobile',
        rule: ['required', 'isMobile'],
        msg: ['请输入手机号', '请输入正确的手机号']
      },
      {
        name: 'provinceId',
        rule: ['required', 'isNum'],
        msg: ['请选择省', '省编码错误']
      },
      {
        name: 'cityId',
        rule: ['required', 'isNum'],
        msg: ['请选择市', '市编码错误']
      },
      {
        name: 'areaId',
        rule: ['required', 'isNum'],
        msg: ['请选择城区', '城区编码错误']
      },
      {
        name: 'address',
        rule: ['required'],
        msg: ['请输收货地址']
      }
    ],
    lists: ['公司', '家', '学校', '其他'],
    region: [],
    showRegion: '请选择城市',
    info: null,
    isDefault: 1
  },
  onLoad: function (options) {
    let id = options.id;
    this.setData({
      id: id,
      delta: Number(options.delta)
    });
    if (id) {
      wx.setNavigationBarTitle({
        title: '更新地址信息',
      });
      wx.util.request('address.detail', {
        body: {id: id}
      }).then(res => {
        let regionArr = res.address_name.split(' ');
        this.setData({
          info: res,
          postData: {
            provinceId: res.province_id,
            cityId: res.city_id,
            areaId: res.area_id,
            postcode: res.zip_code,
          },
          region: [regionArr[0], regionArr[1], regionArr[2]],
          showRegion: res.address_name
        });
      });
    }
  },
  location: function (e) {
    let detail = e.detail;
    let val = detail.value;
    this.setData({
      region: val,
      postData: {
        provinceId: detail.code[0],
        cityId: detail.code[1],
        areaId: detail.code[2],
        postcode: detail.postcode,
      },
      showRegion: val[0] + ' ' + val[1] + ' ' + val[2]
    });
  },
  isDefault: function (e) {
    this.setData({
      isDefault: e.detail.value ? 1 : 0
    });
  },
  add: function (e) {
    let d = this.data,
        api = `address.${d.id ? 'modify' : 'new'}`,
        formData = e.detail.value;
    for (let key in d.postData) {
      formData[key] = d.postData[key];
    }
    let checkRes = wx.form.validation(formData, d.rules);
    if (checkRes) {
      wx.util.toast(checkRes);
    } else {
      wx.util.request(api, {
        query: `id=${d.id}`,
        body: {
          post_code: d.postcode,
          province_id: formData.provinceId,
          city_id: formData.cityId,
          area_id: formData.areaId,
          address_details: formData.address,
          realname: formData.name,
          mobile: formData.mobile,
          is_default: d.isDefault
        }
      }).then(() => {
        wx.navigateBack({
          delta: d.delta
        });
      });
    }
  },
  del: function () {
    wx.util.request('address.del', {
      query: 'id=' + this.data.id
    }).then(() => {
      wx.navigateBack();
    });
  }
})